package com.jf.cloud.service.sysmanager.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.entity.CardBatch;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlRowSetResultSetExtractor;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jf.cloud.service.sysmanager.common.base.BaseService;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.dao.ICardOptRecordService;
import com.jf.cloud.service.sysmanager.entity.CardOptRecord;
import com.jf.cloud.service.sysmanager.vo.CardOptUserVO;

import ch.qos.logback.core.joran.conditional.ElseAction;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Created Date 2018/5/28
 * Time: 14:25
 * Description:
 */
@Service
public class CardOptRecordServiceImpl extends BaseService<CardOptRecord, Long> implements ICardOptRecordService {

    /**
     * 日志
     */
    private static Log log = LogFactory.getLog(CardOptRecordServiceImpl.class);

    /**
     * JDBC 模板
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Resource
    private BaseDao basedao;


    @Override
    public List<CardOptUserVO> getCardOptUser(List<Long> userList) {
        if (userList == null || userList.size() == 0) {
            return null;
        }
        String users = StringUtils.join(userList.toArray(), ",");
        log.info(users);
        String sql = String.format("select u.ROW_ID AS rowId,u.USER_NAME AS userName,u.USER_EMAIL AS userEmail,u.PLATFORM_TYPE as platformType,u.EMAIL_PWD as emailPwd,u.PAY_PWD as payPwd,u.LOGIN_PWD as loginPwd," +
                "u.USER_STATUS as userStatus,r.CREATE_TIME as createTime,r.BATCH_ID as batchId,r.OPT_RESULT as optResult,r.TICKET_NUM as ticketNum,r.RECHARGE_NUM as rechargeNum,r.FAIL_REASON as failReason,b.PROJECT_NAME as projectName from" +
                " card_base_user AS u,card_base_batch as b,card_base_opt_record as r where r.USER_ID = u.ROW_ID AND r.BATCH_ID=b.ROW_ID AND u.ROW_ID in (%s) AND r.OPT_RESULT = 0", users);
        List<CardOptUserVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(CardOptUserVO.class));
        return list;
    }


    @Override
    public Paging<CardOptRecord> findPage(OPaging<CardOptRecord> page, String platformType) {
        try {
            if (!StringUtils.isEmpty(platformType)) {
                String sql = "select MAX(ROW_ID) as ID FROM card_base_batch AS b WHERE b.PLATFORM_TYPE = " + platformType;
                SqlRowSet sqlRowSet = jdbcTemplate.query(sql, new SqlRowSetResultSetExtractor());
                long batchId = 0;
                if (sqlRowSet != null && sqlRowSet.next()) {
                    batchId = sqlRowSet.getLong("ID");
                } else {
                    return null;
                }
                page.getWm().put("BATCH_ID", batchId);
            }
            return findPage(page);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Transactional
    @Override
    public Paging<CardOptUserVO> findPage(OPaging<CardOptRecord> page,String userName, String platformType, String projectName) {
        String sql = "SELECT r.ROW_ID AS rowId,r.STAFF_ID AS kfId,r.BATCH_ID AS batchId,r.USER_ID AS userId,r.USER_NAME AS userName,r.OPT_RESULT AS optResult,r.UPDATE_TIME AS updateTime," +
                "r.CREATE_TIME AS createTime,r.TICKET_NUM AS ticketNum,r.RECHARGE_NUM AS rechargeNum,r.FAIL_REASON AS failReason,b.PROJECT_NAME AS projectName,b.PLATFORM_TYPE AS platformType,s.STAFF_ACCOUNT AS kfAccount" +
                " FROM card_base_opt_record AS r RIGHT JOIN card_base_batch AS b ON b.`ROW_ID` = r.BATCH_ID RIGHT JOIN sys_staff AS s ON s.ROW_ID = r.STAFF_ID";
        String countSql = "SELECT count(*) FROM card_base_opt_record AS r RIGHT JOIN card_base_batch AS b ON b.`ROW_ID` = r.BATCH_ID RIGHT JOIN sys_staff AS s ON s.ROW_ID = r.STAFF_ID";
        List list = new ArrayList();
        if (StringUtils.isNotEmpty(userName)) {
            sql = sql + " where r.ROW_ID IS NOT NULL AND r.USER_NAME like ? ";
            countSql = countSql + " where r.ROW_ID IS NOT NULL AND r.USER_NAME like ? ";
            list.add("%" + userName + "%");
            if (StringUtils.isNotEmpty(platformType)) {
                sql = sql + " and b.PLATFORM_TYPE = ?";
                countSql = countSql + " and b.PLATFORM_TYPE = ? ";
                list.add(platformType);
            }
            if (StringUtil.isNotEmpty(projectName)) {
                sql = sql + " and b.PROJECT_NAME LIKE ?";
                countSql = countSql + " and b.PROJECT_NAME LIKE ? ";
                list.add("%" + projectName + "%");
            }
        }else if (StringUtils.isNotEmpty(platformType)) {
            sql = sql + " WHERE b.ROW_ID IS NOT NULL AND b.PLATFORM_TYPE = ? ";
            countSql = countSql + " WHERE b.ROW_ID IS NOT NULL AND b.PLATFORM_TYPE = ? ";
            list.add(platformType);
            if (StringUtil.isNotEmpty(projectName)) {
                sql = sql + " and PROJECT_NAME LIKE ? ";
                countSql = countSql + " and PROJECT_NAME LIKE ? ";
                list.add("%" + projectName + "%");
            }
        } else if (StringUtil.isNotEmpty(projectName)) {
            sql += " WHERE b.ROW_ID IS NOT NULL AND b.PROJECT_NAME LIKE ? ";
            countSql += " WHERE b.ROW_ID IS NOT NULL AND b.PROJECT_NAME LIKE ? ";
            list.add("%" + projectName + "%");
        } else {
        	sql += " WHERE b.ROW_ID IS NOT NULL ";
        	countSql += " WHERE b.ROW_ID IS NOT NULL ";
		}
        int count = basedao.findCount(countSql,list.toArray());
        sql = sql + " order by r.CREATE_TIME DESC limit ?, ?";
        list.add(page.getOffset());
        list.add(page.getLimit());
        List<CardOptUserVO> resultList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(CardOptUserVO.class),list.toArray());
        Paging<CardOptUserVO> paging = new Paging<CardOptUserVO>(count,page.getCurPage(),page.getLimit());
        paging.setDataList(resultList);
        return paging;
    }

    @Override
    @Transactional
    public boolean optResult(Long rowId, Integer resultCode, String remark, String ticket, String recharge,Long failId,Long platformType,Long staffId) {
        //String sql = "select ROW_ID as ID FROM card_base_opt_record AS r WHERE r.USER_ID = ? AND r.BATCH_ID = (select max(BATCH_ID) FROM card_base_opt_record)";
    	String sql = "select MAX(ROW_ID) as ID FROM card_base_opt_record AS r WHERE r.USER_ID = ? AND r.BATCH_ID = (select max(ROW_ID) FROM card_base_batch WHERE PLATFORM_TYPE = ?)";
        SqlRowSet sqlRowSet = jdbcTemplate.query(sql,new SqlRowSetResultSetExtractor(),rowId,platformType);
        long optId = 0;
        if (sqlRowSet != null && sqlRowSet.next()) {
            optId = sqlRowSet.getLong("ID");
            sql = "update card_base_opt_record set OPT_RESULT = ?,FAIL_REASON = ?,TICKET_NUM = ?,RECHARGE_NUM = ? ,UPDATE_TIME=? where ROW_ID = ? and OPT_RESULT = 0";
            String date = DateUtil.getCurrentDateTime();
            int count = jdbcTemplate.update(sql, resultCode, remark, ticket, recharge, date, optId);
            if (count > 0) {
            	// roway 更新用户表	resultCode	1 成功，2，失败
            	String userSql = "update card_base_user set LAST_OPT_TIME = ?,KF_ID = null,KF_ACCOUNT='',PROJECT_NAME='' where ROW_ID = ? and USER_STATUS = 1 and KF_ID = ?";
            	if("2".equals(resultCode.toString())){
            		userSql = "update card_base_user set USER_ENABLE =2,LAST_OPT_TIME = ?,KF_ID = null,KF_ACCOUNT='',FAIL_ID = ?,FAIL_REASON = ?,FAIL_TIME = ? where ROW_ID = ? and USER_STATUS = 1 and KF_ID = ?";
            		return basedao.safeUpdate(userSql, 1, DateUtil.getCurrentDateTime(),failId,remark,DateUtil.getCurrentDateTime(),rowId,staffId);
            	}else{
            		return basedao.safeUpdate(userSql, 1, DateUtil.getCurrentDateTime(),rowId,staffId);
            	}
                
            }
        }
        return false;
    }


}
